'use strict';

const { Service } = require('ee-core');
const Services = require('ee-core/services');
const Log = require('ee-core/log');
const captureScreen = require('screenshot-desktop');
const { getDateStr, getTimeStr } = require('../utils/dateUtils')
const FormData = require('form-data'); // 引入FormData模块
const fs = require('fs'); 
const os = require('os');
const Conf = require('ee-core/config');
const path = require('path');

const cfg = Conf.getValue('main');


/**
 * api
 * @class
 */
class ApiService extends Service {

  constructor(ctx) {
    super(ctx);
	this.deviceCode = '';
  }

  packageBody(body) {
    let header = {
  	senddate: getDateStr(),
  	sendtime: getTimeStr(),
  	devicecode: this.deviceCode,
  	version: '1.0',
  	token: 'token',
  	serialno: '123456780'
    };
    return {header, body};
  }

  /**
   * 签到
   */
  async signIn() {
	let body = {};
	// 獲取mac
	let {mac, ip} = Services.get('device').getIpAndMacAddr();
	body.deviceip = ip;
	body.devicemac = mac;
	if (os.type() == 'Windows_NT') {
		//windows平台
		body.systemname = "Windows";
	} else if (os.type() == 'Darwin') {
		//mac
		body.systemname = "IOS";
	} else if (os.type() == 'Linux') {
		//Linux平台
		body.systemname = "Linux";
	} else {
		body.systemname = "Others";
	}
	  body.resolution = Services.get('device').getScreenResolution();
	  body.uuid = Services.get('device').getMachineId();
	  const data = this.packageBody(body);
	  Log.info("sign请求参数:"+ JSON.stringify(data))
	  let res = await Services.get('request').request({
		url: 'httpcommon/signin',
		method: 'post',
		data: data
	  })
	if (res && res.code == 0) {
		this.deviceCode = res.data.devicecode;
		Log.info("deviceCode:"+ this.deviceCode)
	}
	return res;
  }
                                                    
  /**
   * 上传设备状态
   */
  uploadDeviceStatus(deviceCode) {
	  let body = {};
	  body.devicestatus = '0';
	  const data = this.packageBody(body);
	  // Log.info("uploadDeviceStatus请求参数:"+ JSON.stringify(data))
	  return Services.get('request').request({
	  		url: 'httpcommon/uploadstatus',
	  		method: 'post',
	  		data: data
	  })
  }
  
  /** 获取节目信息
   * @param {Object} deviceCode
   * @param {Object} id
   */
  getProgramInfo(deviceCode, id) {
	let body = {};
	body.programid = id;
	const data = this.packageBody(body);
	Log.info("getProgramInfo请求参数:"+ JSON.stringify(data))
	return Services.get('request').request({
			url: 'httpcommon/getprogram',
			method: 'post',
			data: data
	})  
  }

  /**
   * 上传节目更新状态
   * @param {String} programRecordId 
   * @param {String} programStatus 
   */
  uploadProgramStatus(programRecordId, programStatus) {
	let body = {};
	body.programRecordId = programRecordId;
	body.programStatus = programStatus;
	const data = this.packageBody(body);
	Log.info("uploadProgramStatus请求参数:"+ JSON.stringify(data))
	return Services.get('request').request({
			url: 'httpcommon/uploadProgramStatus',
			method: 'post',
			data: data
	})  
  }
      
	/**
	 * 截图并上传
	 */
	screenShot() {
		// 调用函数进行截图
		captureScreen({filename: path.join(cfg.mainPath, 'shot.jpg')}).then((imgPath) => {
			Log.info('shot screen:' + imgPath)
			let formData = new FormData();
			// 将要上传的图片文件添加到FormData中
			formData.append('file_data', fs.createReadStream(imgPath));
			formData.append('useSameName', '0');
			formData.append('deviceCode', this.deviceCode);
			Services.get('request').request({
				url: 'httpcommon/uploadFile',
				method: 'post',
				data: formData,
				headers: {
					...formData.getHeaders() // 获取表单数据的头部信息
				}
			}).then(res => {
				if (res.code == 0) {
					this.uploadMonitorInfo(res.data.fileUrl);
				} else {
					Log.error("上传桌面截图失败:"+res.msg||res.desc)
				}
				console.log(res);
			}).catch(error => {
				Log.error("上传桌面截图异常:"+error)
			})
		}).catch((error) => {
			console.error(`截图失败：${error}`);
		});
	}

	/**
	 * 上传监控信息
	 * @param {String} pagePic 
	 * @returns 
	 */
	uploadMonitorInfo(pagePic) {
		let body = {};
		body.pagePic = pagePic;
		let {freeMemoryGb, totalMemoryGb} = Services.get('os').getOsMemory();
		let monitorData = [];
		let jItem = {};
		jItem.lbl = "版本编码"
		jItem.val = cfg.version.code;
		monitorData.push(jItem);
		
		jItem = new Object()
		jItem.lbl = "版本名称"
		jItem.val = cfg.version.name;
		monitorData.push(jItem);

		jItem = new Object()
		jItem.lbl = "可用内存"
		jItem.val = freeMemoryGb
		monitorData.push(jItem);

		jItem = new Object()
		jItem.lbl = "总内存"
		jItem.val = totalMemoryGb;
		monitorData.push(jItem);

		
		body.monitorData = JSON.stringify(monitorData);
		const data = this.packageBody(body);
		Log.info("uploadMonitorInfo请求参数:"+ JSON.stringify(data))
		return Services.get('request').request({
				url: 'httpcommon/uploadMonitorInfo',
				method: 'post',
				data: data
		})  	
	}

}

ApiService.toString = () => '[class ApiService]';
module.exports = ApiService;  